/*
 * @Description:
 * @User: Vijay <1937832819@qq.com>
 * @Date: 2020-10-20 22:34:11
 */
package admin

import (
	"blogApi/controllers"
	. "blogApi/models"
	"encoding/json"
	"html"
	"os"
	"strconv"
	"strings"
)

// ArticleController 文章控制器
type ArticleController struct {
	controllers.BaseController
}

// Index 获取文章列表
func (cont *ArticleController) Index() {
	page, pageErr := cont.GetInt("page")
	limit, limitErr := cont.GetInt("limit")
	keywords := strings.TrimSpace(cont.GetString("keywords"))
	status, statusErr := cont.GetInt("status")
	category_id, categoryErr := cont.GetInt("categoryId")
	query := Db.Model(&Article{})
	if pageErr != nil {
		page = 1
	}
	if limitErr != nil {
		limit = 10
	}
	if categoryErr == nil {
		query.Where("category_id = ?", category_id)
	}
	if statusErr == nil {
		query.Where("status = ?", status)
	}
	if keywords != "" {
		query.Where(Db.Where("title LIKE ?", "%"+keywords+"%").Or("author LIKE ?", "%"+keywords+"%"))
	}
	offset := (page - 1) * limit
	// 总数
	var total int64
	query.Count(&total)
	// 返回数据
	list := make([]*Article, 0)
	query.Debug().Order("id desc").Offset(offset).Limit(limit).Find(&list)
	resMap := make(map[string]interface{})
	resMap["list"] = list
	resMap["total"] = total
	cont.ResJson(0, "获取成功", resMap, nil)
}

// 查询
func (cont *ArticleController) Info() {
	if cont.Ctx.Input.IsGet() == false {
		cont.ResJson(1, "请求方式错误", nil, nil)
	}
	id := cont.Input().Get("id")
	var input Article
	if result := Db.Debug().First(&input, id); result.Error != nil {
		cont.ResJson(1, "操作失败", result.Error, nil)
	}
	cont.ResJson(0, "操作成功", input, nil)
}

// Store 创建文章
func (cont *ArticleController) Store() {
	if cont.Ctx.Input.IsPost() == false {
		cont.ResJson(1, "请求方式错误", nil, nil)
	}
	var input Article
	var err error
	if err = json.Unmarshal(cont.Ctx.Input.RequestBody, &input); err != nil {
		cont.ResJson(1, "失败", input, nil)
	}
	// 验证
	if msg := input.SelfValid(); msg != nil {
		cont.ResJson(1, msg, input, nil)
	}
	// 转义
	input.Content = html.EscapeString(input.Content)
	if result := Db.Debug().Create(&input); result.Error != nil {
		cont.ResJson(1, "操作失败", result.Error, nil)
	}
	cont.ResJson(0, "操作成功", input, nil)
}

func (cont *ArticleController) Update() {
	if cont.Ctx.Input.IsPut() == false {
		cont.ResJson(1, "请求方式错误", nil, nil)
	}
	var input Article
	// 接收参数
	if err := cont.ParseForm(&input); err != nil {
		cont.ResJson(1, "参数解析失败", nil, nil)
	}
	// 验证
	if msg := input.SelfValid(); msg != nil {
		cont.ResJson(1, msg, input, nil)
	}
	if result := Db.Model(&Article{}).Where("id = ?", input.Id).Select("slug", "categoryId", "title", "author", "content", "markdown", "description", "keywords", "status", "cover", "isTop", "click", "updatedAt").Updates(input); result.Error != nil {
		cont.ResJson(1, "存入失败", result.Error, nil)
	}
	cont.ResJson(0, "操作成功", input, nil)
}

// 删除
func (cont *ArticleController) Destroy() {
	if cont.Ctx.Input.IsDelete() == false {
		cont.ResJson(1, "请求方式错误", nil, nil)
	}
	id := cont.Input().Get("id")
	var input Article
	if result := Db.Where("id = ?", id).Delete(&input); result.Error != nil {
		cont.ResJson(1, "操作失败", result.Error, nil)
	}
	cont.ResJson(0, "操作成功", input, nil)
}

// Upload 图片上传
func (cont *ArticleController) Upload() {
	f, h, err := cont.GetFile("file")
	if err != nil {
		cont.ResJson(1, "获取文件失败", err, nil)
	}
	defer f.Close()
	filePath := "static/upload/"
	fileName := h.Filename
	host := cont.Ctx.Input.Site()
	port := strconv.Itoa(cont.Ctx.Input.Port())
	host = host + ":" + port
	file := host + "/" + filePath + fileName
	// 不存在就创建目录
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		os.Mkdir(filePath, os.ModePerm)
	}
	error := cont.SaveToFile("file", filePath+fileName) // 保存位置在 static/upload, 没有文件夹要先创建
	if error != nil {
		cont.ResJson(1, "保存失败", error, nil)
	}
	cont.ResJson(0, "请求成功", file, nil)
}
